import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    cartList: []
  },
  mutations: {
    updateCheckedById(state, id){
      state.cartList.some(item => {
        if(item.id===id){
          return item.checked = !item.checked
        }
      })
    },
    allClick(state){
      if(this.getters.isAllChecked){
        state.cartList.forEach(t => t.checked=false)
      }else{
        state.cartList.forEach(t => t.checked=true)
      }
      // state.cartList.some(t => !t.checked)
      console.log(this.getters.isAllChecked);
    }
  },
  getters: {
    cartLength(state){
      return state.cartList.length
    },
    cartList(state){
      return state.cartList
    },
    sumPrice(state){
      return state.cartList.filter(t => t.checked).reduce((pre, item) => {
        return pre + item.price * item.count
      }, 0).toFixed(2)
    },
    checkLength(state){
      return state.cartList.filter(t => t.checked).length
    },
    isAllChecked(state){
      // 如果没有商品，直接返回false
      if(!state.cartList.length) return false

      // 如果有一个为false未选中，some返回true，取反返回false
      return !state.cartList.some(item => !item.checked)
    }
  },
  actions: {
    addCart({ state }, obj){
      console.log(123);

      return new Promise((resolve, reject) => {
        var ret = state.cartList.some(item => {
          if(item.id===obj.id){
            item.count++
            resolve('商品数量+1')
            return true
          }
        })


        if(!ret){
          obj.checked = true
          state.cartList.push(obj)
          resolve('添加了新商品')
        }
      })
    }
  }
})

export default store
